package com.logos.reflect;

import com.logos.entity.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;

public class ConstructTest {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 获取Class对象
        Class<?> clazz = Class.forName("com.logos.entity.Student");
        // 获取公关构造方法
        Constructor[] constructors = clazz.getConstructors();
//        for (Constructor constructor : constructors) {
//            System.out.println(constructor);
//        }
        // 获取所有构造方法
        Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
//        for (Constructor declaredConstructor : declaredConstructors) {
//            System.out.println(declaredConstructor);
//        }
        // 获取单个构造方法
        Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class);
        int modifiers = declaredConstructor.getModifiers();
        System.out.println("modifiers = " + modifiers);
        Parameter[] parameters = declaredConstructor.getParameters();
        for (Parameter parameter : parameters) {
            System.out.println(parameter);
        }
        // 暴力反射，取消访问检查
        declaredConstructor.setAccessible(true);
        Student stu = (Student) declaredConstructor.newInstance("logos");
        System.out.println(stu);
    }
}
